package br.com.virtual.base.uteis;


import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class CDIFactory {

	private static BeanManager getBeanManager() {
		try {
			InitialContext initialContext = new InitialContext();
			return (BeanManager) initialContext.lookup("java:comp/BeanManager");
		} catch (NamingException e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(Class<T> beanClass) {
		BeanManager bm = getBeanManager();
		Bean<?> userDataBean = bm.resolve(bm.getBeans(beanClass));

		return (T) bm.getReference(userDataBean, beanClass,
				bm.createCreationalContext(userDataBean));
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(Class<T> returnClass, String name) {
        BeanManager bm = getBeanManager();
        Bean<?> bean = bm.getBeans(name).iterator().next();
        CreationalContext<?> ctx = bm.createCreationalContext(bean);
        
        return (T) bm.getReference(bean, bean.getClass(), ctx);
    }
}
